package com.promise.jokerdream.work.signin.before

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 徒弟工作
class ApprenticeWork(override val uin: String): BaseWork(uin) {

    override val name: String
        get() = "徒弟"

    override val priority: Int
        get() = 1

    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        try {
            // 查询企鹅信息
            val penguinInfoResult = gameApi.queryPenguinInfo(uin)
            return penguinInfoResult.foldWithApiException(
                onSuccess = { penguinResponse ->
                    if (penguinResponse.baseInfo.expflag == 1 && penguinResponse.hasTudi()) {
                        val apprenticeExpResult = gameApi.getApprenticeExperience()
                        apprenticeExpResult.foldWithApiException(
                            onSuccess = { expResponse ->
                                historyManager.addHistory(name, expResponse.getDescription())
                                WorkResult.Success
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                                WorkResult.Failure(Exception(msg), msg)
                            }
                        )
                    } else {
                        WorkResult.Success
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            return WorkResult.Failure(e, e.message)
        }
    }
}